package com.baox.agridata.synchronous.schedule;


import com.baox.agridata.synchronous.assembly.TCCOutAAAssembly;
import com.baox.agridata.synchronous.assembly.TCCOutPAAssembly;
import com.baox.agridata.synchronous.constant.Constant;
import com.baox.agridata.synchronous.constant.TaskNameConstant;
import com.baox.agridata.synchronous.entity.quanguo.Jyzscpb;
import com.baox.agridata.synchronous.entity.quanguo.Jyzsdwb;
import com.baox.agridata.synchronous.entity.shanxi.SxAgricultureTask;
import com.baox.agridata.synchronous.entity.shanxi.TCCOutAAEntity;
import com.baox.agridata.synchronous.entity.shanxi.TCCOutPAEntity;
import com.baox.agridata.synchronous.service.quanguo.JyzQGcpaService;
import com.baox.agridata.synchronous.service.quanguo.JyzQGdwaService;
import com.baox.agridata.synchronous.service.shanxi.*;
import com.baox.agridata.synchronous.util.DateUtil;
import com.baox.agridata.synchronous.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 动物卫生监督管理平台----农业部的推送
 */


@Slf4j
@Component
@Configuration
public class LocalPushDataToAgriculturalDepartment {


    @Autowired
    private SxAgricultureTaskService sxAgricultureTaskService;


    @Autowired
    private TBaseRegionService tBaseRegionService;

    @Autowired
    private SplitDataSummary splitDataSummary;

    @Autowired
    private TCCABService tccabService;


    @Autowired
    private TCCAAService tccaaService;


    @Autowired
    private TCCPAService tccpaService;


    @Autowired
    private TCCPBService tccpbService;


    @Autowired
    private TCCOutAAService tccOutAAService;

    @Autowired
    private TCCOutPAService tccOutPAService;


    @Autowired
    private JyzQGdwaService jyzQGdwaService;  //全国动物A到达本省


    @Autowired
    private JyzQGcpaService jyzQGcpaService;   //全国产品A到达本省


    @Autowired
    private TCCOutAAAssembly tccOutAAAssembly;

    @Autowired
    private TCCOutPAAssembly tccOutPAAssembly;


    @Value("${DbConfig.CCABStartTime}")
    private String CCABStartTime;


    @Value("${DbConfig.CCAAStartTime}")
    private String CCAAStartTime;


    @Value("${DbConfig.CCPAStartTime}")
    private String CCPAStartTime;


    @Value("${DbConfig.CCPBStartTime}")
    private String CCPBStartTime;

    @Value("${DbConfig.RI1}")
    private String RI1;


    public static Integer PRODUCT_A = 1;
    public static Integer PRODUCT_B = 2;
    public static Integer ANIMAL_A = 1;
    public static Integer ANIMAL_B = 2;

    /**
     * 动物B数据推送
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushCCABToDepartment() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.pushCCABToDepartment);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                Thread.sleep(1000); // 延迟1秒
                log.info("开始【动物B证】定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "CCAB";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, Constant.FILE_NAME)) {
                    CCABStartTime = l_file.readLastLineV2(l_filePath, Constant.FILE_NAME);
                }
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                List<Jyzsdwb> localCCABList = tccabService.getLocalCCABList(CCABStartTime, endTime, null);
                if (localCCABList != null && localCCABList.size() > 0) {
                    Integer result = splitDataSummary.interceptListAnimal(localCCABList, ANIMAL_B);
                    if (result != null && result.intValue() > 0) {
                        log.info("开始【动物B证】定时数据同步,本期开始时间节点为:{},下期开始时间节点为:{},同步数据总条目为：{},数据库插入结果为：{}", CCABStartTime, endTime, localCCABList.size(), result.intValue());
                    }
                } else {
                    log.info("【动物B证】本次未查询到数据,本期时间节点为:{}-----{}", CCABStartTime, endTime);
                }
                l_file.WriteContent(endTime, l_filePath, Constant.FILE_NAME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            log.info("【动物B证】任务未开启");
        }
    }

    /**
     * 动物A数据推送
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushCCAAToDepartment() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.pushCCAAToDepartment);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                Thread.sleep(1000); // 延迟1秒
                log.info("开始动物A证定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "CCAA";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, Constant.FILE_NAME)) {
                    CCAAStartTime = l_file.readLastLineV2(l_filePath, Constant.FILE_NAME);
                }
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                List<Jyzsdwb> localCCAAList = tccaaService.getLocalCCAAList(CCAAStartTime, endTime, null);
                if (localCCAAList != null && localCCAAList.size() > 0) {
                    Integer result = splitDataSummary.interceptListAnimal(localCCAAList, ANIMAL_A);
                    if (result != null && result.intValue() > 0) {
                        log.info("开始动物A证定时数据同步，本期开始时间节点为:{},下期开始时间节点为:{},同步数据总条目为：{},数据库插入结果为：{}", CCAAStartTime, endTime, localCCAAList.size(), result.intValue());
                    }
                } else {
                    log.info("【动物A证】本次未查询到数据,本期时间节点为:{}-----{}", CCAAStartTime, endTime);
                }
                l_file.WriteContent(endTime, l_filePath, Constant.FILE_NAME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            log.info("【动物A证】任务未开启");
        }
    }

    /**
     * 产品A数据推送
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushCCPAToDepartment() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.pushCCPAToDepartment);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                Thread.sleep(1000); // 延迟1秒
                log.info("开始产品A证定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "CCPA";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, Constant.FILE_NAME)) {
                    CCPAStartTime = l_file.readLastLineV2(l_filePath, Constant.FILE_NAME);
                }
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                List<Jyzscpb> localCCPAList = tccpaService.getLocalPCAAList(CCPAStartTime, endTime, null);
                if (localCCPAList != null && localCCPAList.size() > 0) {
                    Integer result = splitDataSummary.interceptListProduct(localCCPAList, PRODUCT_A);
                    if (result != null && result.intValue() > 0) {
                        log.info("开始产品A证定时数据同步，本期开始时间节点为:{},下期开始时间节点为:{},同步数据总条目为：{},数据库插入结果为：{}", CCPAStartTime, endTime, localCCPAList.size(), result.intValue());
                    }
                } else {
                    log.info("【产品A证】本次未查询到数据,本期时间节点为:{}-----{}", CCPAStartTime, endTime);
                }
                l_file.WriteContent(endTime, l_filePath, Constant.FILE_NAME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            log.info("【产品A证】任务未开启");
        }
    }

    /**
     * 产品B数据推送
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pushCCPBToDepartment() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.pushCCPBToDepartment);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                Thread.sleep(1000); // 延迟1秒
                log.info("开始产品B证定时数据同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "CCPB";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, Constant.FILE_NAME)) {
                    CCPBStartTime = l_file.readLastLineV2(l_filePath, Constant.FILE_NAME);
                }
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                List<Jyzscpb> localCCPBList = tccpbService.getLocalCCPBList(CCPBStartTime, endTime, null);
                if (localCCPBList != null && localCCPBList.size() > 0) {
                    Integer result = splitDataSummary.interceptListProduct(localCCPBList, PRODUCT_B);
                    if (result != null && result.intValue() > 0) {
                        log.info("开始产品B证定时数据同步，本期开始时间节点为:{},下期开始时间节点为:{},同步数据总条目为：{},数据库插入结果为：{}", CCPBStartTime, endTime, localCCPBList.size(), result.intValue());
                    }
                } else {
                    log.info("【产品B证】本次未查询到数据,本期时间节点为:{}-----{}", CCPBStartTime, endTime);
                }
                l_file.WriteContent(endTime, l_filePath, Constant.FILE_NAME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            log.info("【产品B证】任务未开启");
        }
    }

    /**
     * 动物A证(本省收到):全国数据到本省的数据接收
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    @Async("newAsyncExecutor")
    public void DestinationCCAATask() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.DestinationCCAATask);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("【农业部外省动物A】开始同步");
            List<Jyzsdwb> l_list = jyzQGdwaService.getJyzqgdwaList();  //去拿全国到达本省的数据A证
            List<TCCOutAAEntity> outAAEntityList = new ArrayList<>();
            if (l_list != null && l_list.size() > 0) {
                for (Jyzsdwb entity : l_list) {
                    Integer regionCount = tBaseRegionService.selectCountBySixRegionCode(entity.getDqhdm(), RI1);  //判断农业推送的数据，是不是目的地为陕西省的数据
                    if (null == regionCount || regionCount.intValue() == 0) continue;
                    Integer isExist = tccOutAAService.selectOutAAIsExistById(entity.getId()); //通过mid查询外省动物A是否存在
                    if (isExist != null && isExist.intValue() > 0) continue;
                    TCCOutAAEntity tccOutAAEntity = tccOutAAAssembly.JyzqgdwaToOutAnimalA(entity);
                    outAAEntityList.add(tccOutAAEntity);
                }
            }
            Integer addResult = 0, deleteCount = 0;
            if (outAAEntityList != null && outAAEntityList.size() > 0) {
                addResult = splitDataSummary.interceptListOutAA(outAAEntityList); ////批量插入外省动物A
                //记录一下外省入省的动物A证数据
                FileUtil l_file = new FileUtil();
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "OutAA";
                List<String> zbhList = outAAEntityList.stream().map(TCCOutAAEntity::getFactoryCode).collect(Collectors.toList());
                l_file.recordData(zbhList, "往前推五分钟", endTime, l_filePath_record);
                if (addResult.intValue() == outAAEntityList.size())
                    //将农业部的数据删除
                    deleteCount = jyzQGdwaService.deleteJyzqgdwaList(l_list);
            } else if (l_list != null && l_list.size() > 0) {
                //将农业部的数据删除
                deleteCount = jyzQGdwaService.deleteJyzqgdwaList(l_list);
            }
            log.info("T_CC_OUT_AA:农业部查询条目数为：{},新增条目数为：{},删除的条目数为：{}", l_list.size(), addResult.intValue(), deleteCount.intValue());
        } else {
            log.info("【农业部外省动物A】任务未开启");
        }
    }

    /**
     * 产品A证(本省收到的):全国数据到本身的产品A证数据
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    @Async("newAsyncExecutor")
    public void DestinationCCPATask() {
        SxAgricultureTask sxAgricultureTask = sxAgricultureTaskService.selectTaskStatus(TaskNameConstant.DestinationCCPATask);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            log.info("【农业部外省产品A】开始同步");
            List<Jyzscpb> l_list = jyzQGcpaService.getJyzQGcpaList();  //查询农业部全国的数据
            List<TCCOutPAEntity> outPAEntityList = new ArrayList<>();
            if (l_list != null && l_list.size() > 0) {
                for (Jyzscpb entity : l_list) {
                    Integer regionCount = tBaseRegionService.selectCountBySixRegionCode(entity.getDqhdm(), RI1);  //判断农业推送的数据，是不是目的地为陕西省的数据
                    if (null == regionCount || regionCount.intValue() == 0) continue;
                    Integer isExist = tccOutPAService.selectOutPAIsExistById(entity.getId()); //通过mid查询外省产品A是否存在
                    if (isExist != null && isExist.intValue() > 0) continue;
                    TCCOutPAEntity tccOutPAEntity = tccOutPAAssembly.JyzqgcpaToOutProductA(entity);
                    outPAEntityList.add(tccOutPAEntity);
                }
            }
            Integer addResult = 0, deleteCount = 0;
            if (outPAEntityList != null & outPAEntityList.size() > 0) {
                addResult = splitDataSummary.interceptListOutPA(outPAEntityList); //批量插入外省产品A
                //记录一下外省入省的动物A证数据
                FileUtil l_file = new FileUtil();
                String endTime = DateUtil.dateToMinute(new Date()) + ":00";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "OutPA";
                List<String> zbhList = outPAEntityList.stream().map(TCCOutPAEntity::getFactoryCode).collect(Collectors.toList());
                l_file.recordData(zbhList, "往前推五分钟", endTime, l_filePath_record);
                if (addResult.intValue() == outPAEntityList.size())
                    deleteCount = jyzQGcpaService.deleteJyzqgcpaList(l_list); //将农业部的数据删除
            } else if (l_list != null && l_list.size() > 0) {
                deleteCount = jyzQGcpaService.deleteJyzqgcpaList(l_list); //将农业部的数据删除
            }
            log.info("T_CC_OUT_PA:农业部查询条目数为：{},新增条目数为：{},删除的条目数为：{}", l_list.size(), addResult.intValue(), deleteCount.intValue());
        } else {
            log.info("【农业部外省产品A】任务未开启");
        }
    }


}
